
#ifndef CONNECTIONPOOL_H
#define CONNECTIONPOOL_H
#include <QQueue>
#include <QMutex>
#include <QSqlDatabase>
#include <QSqlError>

class ConnectionPool
{
public:
    static ConnectionPool& instance()
    {
        static ConnectionPool pool;
        return pool;
    }

    QSqlDatabase getConnection()
    {
        QMutexLocker lock(&m_mutex);
        if (m_connections.isEmpty())
        {
            createNewConnection();
        }
        return m_connections.dequeue();
    }

    void releaseConnection(QSqlDatabase conn)
    {
        QMutexLocker lock(&m_mutex);
        m_connections.enqueue(conn);
    }

private:
    void createNewConnection()
    {
        QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");//加载MySQL数据库驱动
        db.setDatabaseName("test");
        db.setHostName("localhost");
        db.setUserName("root");
        db.setPassword("123456");
        db.setPort(3306);
        if (!db.open())
        {
            qDebug() << "DB connection failed:" << db.lastError();
        }
        m_connections.enqueue(db);
    }

    QQueue<QSqlDatabase> m_connections;
    QMutex m_mutex;
    int m_count = 0;
};
#endif
